/*
 * Copyright (c) 2023, 2023,yzc.cn All rights reserved.
 *
 */
package cn.yzc;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * <p>Project: RabbitMQ - Publisher</p>
 * <p>Powered by yzc On 2023-12-19 15:51:27</p>
 * <p>描述：<p>
 *
 * @author yzc [yzc0415@126.com]
 * @version 1.0
 * @since 17
 */

/**
 * 生产者
 */
public class Publisher {
    public static void main(String[] args) throws IOException, TimeoutException {

        //1.创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //设置虚拟机的名称
        factory.setVirtualHost("/");
        //用户名
        factory.setUsername("admin");
        //密码
        factory.setPassword("5672");
        //设置端口好
        factory.setPort(5672);
        //设置mq服务器地址
        factory.setHost("127.0.0.1");

        //2.创建连接
        Connection conn = factory.newConnection();

        //3.创建信道
        Channel channel = conn.createChannel();

        //声明死信队列
        String qname = "deadQueue";
        channel.queueDeclare(qname,true,false,false,null);
        //声明死信交换机
        String ex2 = "dead-ex";
        channel.exchangeDeclare(ex2,BuiltinExchangeType.DIRECT);//路由键
        //绑定
        channel.queueBind(qname,ex2,"normal");


        //4.声明正常队列
        String queueName = "normalQueue";
        //正常队列声明时  指明死信交换机
        Map<String,Object> argMap = new HashMap<>();
        argMap.put("x-dead-letter-exchange",ex2);//指定死信交换机的名称
        channel.queueDeclare(queueName,true,false,false,argMap);

        //声明正常的交换机
        String ex = "normal-ex";
        channel.exchangeDeclare(ex,BuiltinExchangeType.DIRECT);//路由键

        //正常队列绑定
        channel.queueBind(queueName,ex,"normal");

        //5.发送消息
        String msg = "hello word";
        AMQP.BasicProperties props = new AMQP.BasicProperties();
        props=props.builder()
                .expiration("10000") //设置消息TTL
                        .build();
        channel.basicPublish(ex,"normal",props,msg.getBytes(StandardCharsets.UTF_8));

        //6.关闭连接 释放资源
        conn.close();

        System.out.println("消息发送完毕.....");

    }
}
